﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TextPreview
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        public string Path { get; set; } = "";
        public string Format { get; set; } = "ASCII";
        public int Length { get; set; } = 1000;
        public string TextPosition { get; set; } = "-";

        public event PropertyChangedEventHandler PropertyChanged;
        void RaisePropertyChangeEvent(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dia = new OpenFileDialog();
            if (dia.ShowDialog()==true)
            {
                Path = dia.FileName;
                RaisePropertyChangeEvent("Path");
            }
        }

        private void BtnGo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (File.Exists(Path) && Length > 0)
                {
                    var format = Encoding.GetEncoding(Format);
                    var stream = File.Open(Path, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(stream, format);
                    var chars = new char[Length];
                    sr.Read(chars, 0, Length);
                    PreviewBox.Text = new string(chars);
                    sr.Close();
                }
                else
                {
                    MessageBox.Show("文件不存在 或 长度非法");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void PreviewBox_MouseMove(object sender, MouseEventArgs e)
        {
            var pos = PreviewBox.GetPositionFromPoint(e.GetPosition(PreviewBox), true);
            var col = pos.GetOffsetToPosition(pos.GetLineStartPosition(0));
            int line = 0;
            pos.GetLineStartPosition(-999999, out line);
            TextPosition = $"line: {1-line}  col: {-col}";
            RaisePropertyChangeEvent("TextPosition");
        }
    }
}
